//
//  VideoListVC.m
//  VideoPlayer
//
//  Created by 白璐 on 16/9/18.
//  Copyright © 2016年 baidu. All rights reserved.
//

#import "VideoListVC.h"
#import "VideoListViewModel.h"
#import "VideoMediaCell.h"
#import "BubbleView.h"
#import "AddVideoView.h"
#import "PlayerVC.h"
#import "PlayerViewModel.h"

@interface VideoListVC () <UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet BubbleView *bubble;
@property (strong, nonatomic) IBOutlet AddVideoView *addView;

@property(nonatomic, strong) VideoListViewModel* viewModel;
@end

@implementation VideoListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.delegate = self;
    
    // setup ui
    self.tableView.allowsMultipleSelectionDuringEditing = NO;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    UIImage* image = [UIImage imageNamed:@"button_add"];
    self.navigationItem.rightBarButtonItem.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    __weak typeof(self) wself= self;
    self.bubble.addBlock = ^{
        __strong typeof(wself) sself = wself;
        [sself showAddUI];
    };
    
    self.bubble.downloadListBlock = ^{
        __strong typeof(wself) sself = wself;
        [sself showDownloadList];
    };
    
    self.addView.addVideoBlock = ^(NSString* name, NSString* url) {
        __strong typeof(wself) sself = wself;
        [sself addVideo:name url:url];
    };
    
    // setup model
    self.viewModel = [[VideoListViewModel alloc] init];
}
- (BOOL)prefersStatusBarHidden {
    return NO;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.bubble.frame = self.view.bounds;
    self.addView.frame = self.view.bounds;
    
    [self.bubble setNeedsDisplay];
}

- (IBAction)onMoreActions:(id)sender {
    if ([self.view.subviews containsObject:self.bubble]) {
        [self.bubble removeFromSuperview];
    } else {
        [self.view addSubview:self.bubble];
    }
}

- (void)onDownload:(VideoMediaCell*)cell {
    // get index path
    CGPoint point = [self.tableView convertPoint:cell.center fromView:cell.superview];
    NSIndexPath* path = [self.tableView indexPathForRowAtPoint:point];
    
    __weak typeof(self) wself = self;
    [self.viewModel download:path.row cancelBlock:^(BOOL cancel) {
        if (cancel) {
            return;
        }
        // update ui
        [wself.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationNone];
        
        // calc origin frame
        CGRect originFrame = [wself.view convertRect:cell.frame fromView:cell.superview];
        
        // calc to point
        UIView* moreView = ((UIViewController*)(wself.navigationItem.rightBarButtonItem)).view;
        CGPoint toPoint = CGPointMake(moreView.frame.size.width / 2, moreView.frame.size.height / 2);
        toPoint = [wself.view convertPoint:toPoint fromView:moreView];
        
        // cala animate duration
        CGFloat interval = (originFrame.origin.y - toPoint.y) / wself.view.frame.size.height;
        interval = fmaxf(0.4f, interval);
        interval = fminf(0.6f, interval);
        
        // snapshot cell
        UIView* cloneCell = [cell snapshotViewAfterScreenUpdates:YES];
        
        // run animate
        cloneCell.frame = originFrame;
        [wself.view addSubview:cloneCell];
        [UIView animateWithDuration:interval animations:^{
            cloneCell.frame = CGRectMake(toPoint.x, toPoint.y, 1, 1);
        } completion:^(BOOL finished) {
            [cloneCell removeFromSuperview];
        }];
    }];
}

- (IBAction)onTapBubbleBlank:(id)sender {
    [self.bubble removeFromSuperview];
}

- (IBAction)onTapAddViewBlank:(id)sender {
    [self.addView closeKeyboard];
}

- (void)showAddUI {
    [self.view addSubview:self.addView];
    [self onTapBubbleBlank:nil];
}

- (void)showDownloadList {
    [self onTapBubbleBlank:nil];
}

- (void)addVideo:(NSString*)name url:(NSString*)url {
    // update model
    NSUInteger count = [self.viewModel count];
    [self.viewModel add:name url:url];
    
    // update ui
    NSIndexPath* path = [NSIndexPath indexPathForRow:count inSection:0];
    
    if (count != 0) {
        [self.tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationBottom];
    } else {
        [self.tableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationNone];
    }
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSUInteger count = [self.viewModel count];
    return count == 0 ? 1 : count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger count = [self.viewModel count];
    if (count == 0) {
        return [tableView dequeueReusableCellWithIdentifier:@"noVideoCell" forIndexPath:indexPath];
    }
    
    VideoMediaCell *cell = (VideoMediaCell*)[tableView dequeueReusableCellWithIdentifier:@"onlineCell" forIndexPath:indexPath];
    __weak typeof(self) wself = self;
    if (!cell.downloadBlock) {
        cell.downloadBlock = ^(VideoMediaCell* cell) {
            __strong typeof(wself) sself = wself;
            [sself onDownload:cell];
        };
    }
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView
            commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
            forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.viewModel deleteVideo:indexPath.row];
        NSUInteger count = [self.viewModel count];
        if (count != 0) {
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        } else {
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        }
    }
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger count = [self.viewModel count];
    return count != 0 ? 100 : 300;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)tableView:(UITableView *)tableView
            willDisplayCell:(UITableViewCell *)cell
            forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger count = [self.viewModel count];
    if (count == 0) {
        return;
    }
    
    NSUInteger row = indexPath.row;
    VideoMediaCell *videoCell = (VideoMediaCell*)cell;
    videoCell.videoImageView.image = [UIImage imageNamed:[self.viewModel image:row]];
    videoCell.titleView.text = [self.viewModel title:row];
    videoCell.detailView.text = [self.viewModel detail:row];
    videoCell.downloadButton.hidden = ![self.viewModel isDownloadableResource:row] || [self.viewModel isDownloading:row];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController
            willShowViewController:(UIViewController *)viewController
            animated:(BOOL)animated {
    if (viewController == self) {
        [self.tableView reloadData];
    }
}

#pragma mark - segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // get index
    UITableViewCell* cell = (UITableViewCell*)sender;
    CGPoint point = [self.tableView convertPoint:cell.center fromView:cell.superview];
    NSIndexPath* path = [self.tableView indexPathForRowAtPoint:point];
    NSUInteger row = path.row;
    
    // get url title
    NSString* url = [self.viewModel url:row];
    NSString* title = [self.viewModel title:row];
    NSString* token = [self.viewModel token:row];
    BOOL downloadable = [self.viewModel isDownloadableResource:row] && ![self.viewModel isDownloading:row];
//http://vod.jxzsxx.com//mda-idnmgfj6dr2sp7dq//mda-idnmgfj6dr2sp7dq.mp4
    PlayerViewModel* viewModel = [[PlayerViewModel alloc] initWithURL:@"http://vod.jxzsxx.com/mda-ijhf90r279wt4c1i/mda-ijhf90r279wt4c1i.m3u8"
                                                                title:title
                                                         downloadable:downloadable
                                                                token:@"72f20fe617fe382ccc9b4507bded7ca8aa1b5744d41918bc5c11a6e1a4686539_b646c31fd8924ae199580a1bc16875dd_1546185600"];
    viewModel.videoSource = self.viewModel;
    
    PlayerVC* vc = (PlayerVC*)segue.destinationViewController;
    vc.viewModel = viewModel;
}

@end
